<?php if (!defined("_ECRIRE_INC_VERSION")) return; if (class_exists('AlohacartPaymentLiqpay')) return;
/**
 * Aloha Cart
 *
 * @author     Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com)
 * @license    GNU/GPL
 * @package    plugins
 * @subpackage alohacart
 * @copyright  (c) Aleksey Yaroshchuk 2011-2012
 * @link       http://www.spip-contrib.net/AlohaCart
 */

/** 
 *  This class provides Liqpay payment logic
 *
 *  @author Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com)
 */
include_spip('functions/pdk_common');
pdk_load_class('AlohacartExtension', 'classes'); 
class AlohacartPaymentLiqpay extends AlohacartExtension {
    public $fields = array('merchant_id', 'merchant_sig', 'id_order_statut_after_payment', 'pay_ways', 'result_url', 'server_url');
    
    public function __construct() {
        parent::__construct();
        $this->configExtension();
    }
    
    private function configExtension(){
        $this->type = 'payment';
        $this->code = 'liqpay';
        $this->isPayable = true;
        
        // Define validation rules:         
         $this->validation->set_rules( 
            array(
                array(
                     'field'   => 'merchant_id',
                     'label'   => _T('alohacart_payment_liqpay:merchant_id'),
                     'rules'   => 'required'
                  ),
                array(
                     'field'   => 'merchant_sig',
                     'label'   => _T('alohacart_payment_liqpay:merchant_sig'),
                     'rules'   => 'required'
                  ),
				array(
                     'field'   => 'pay_ways',
                     'label'   => _T('alohacart_payment_liqpay:pay_way'),
                     'rules'   => ''
                  ),	  
            )
         );
    }
    
    public function GetData($options=array()) {
        // Try to get id_order from $options array or request
        if ($options['id_order']) $id_order = $options['id_order'];
        if (!$id_order && _request('id_order')) $id_order = _request('id_order');
        if (!$id_order) return '';
        
        $data = $this->GetMetaData();  
        
        $order_mdl = pdk_load_class('AlohacartOrderModel', 'classes/');
        $currency_mdl = pdk_load_class('CurrencyModel','classes/');
        
        $order = $order_mdl->select_by_id($id_order);
		
		if (!$order) return '';
		
		// Convert price from main currency into order's currency
		$currency = $currency_mdl->select_by_id($order['id_currency']);
        if (!$currency) return;
        $total_price = $currency_mdl->ConvertPrice($order['total_price'], $currency_mdl->GetMainCurrencyId(), $order['id_currency']);
		//include_spip('inc/charsets');
		$xml="<request>      
      <version>1.2</version>
      <merchant_id>".$data['merchant_id']."</merchant_id>
      <result_url>".urlencode($data['result_url'])."</result_url>
      <server_url>".urlencode($data['server_url'])."</server_url>
      <order_id>".$order['id_order']."</order_id>
      <amount>".$total_price."</amount>
      <currency>".$currency['code']."</currency>
      <description>"./*translitteration(*/_T('alohacart_payment_liqpay:payment_description', array('nom_site_spip'=>extraire_multi($GLOBALS['meta']['nom_site'])))/*)*/."</description>
      <default_phone>".$order['phone']."</default_phone>
      <pay_way>".implode(',', $data['pay_ways'])."</pay_way>      
		</request>";
		
        // Create signature and encode xml:
		$signature = base64_encode(sha1($data['merchant_sig'].$xml.$data['merchant_sig'],1));
        $xml_encoded=base64_encode($xml);
              
        return recuperer_fond('inc/payment/alohacart_liqpay',
			array('signature'=>$signature, 'xml_encoded'=>$xml_encoded));
    }
    
    /**
     *  Checks signature of status data
     *  @param array $status_data Status data
     *  @return bool
     */
    public function CheckSignature($status_data) {
        $meta_data = $this->GetMetaData();        
        $xml_decoded = base64_decode($status_data['operation_xml']);
        $signature=base64_encode(sha1($meta_data['merchant_sig'].$xml_decoded.$meta_data['merchant_sig'],1));
        
        if($status_data['signature'] === $signature) 
            return true;
        else
            return false;
    }
    
    /**
     *  Creates payment text data (info), that can be written into DB orders table
     *  @param array $data Array of data, from wich payment data will be created 
     */
    public function CreatePaymentData($data) {
		return base64_decode($data['operation_xml']);
		// Можно и так
		/*
        $string = '';        
        $string .= $version = $this->GetTag($xml_decoded, 'version')?_T('alohacart_payment_liqpay:version').': '.$version."\n":'';
        $string .= $merchant_id = $this->GetTag($xml_decoded, 'merchant_id')?_T('alohacart_payment_liqpay:merchant_id').': '.$merchant_id."\n":'';
		$string .= $order_id = $this->GetTag($xml_decoded, 'order_id')?_T('alohacart_payment_liqpay:order_id').': '.$order_id."\n":'';
		$string .= $amount = $this->GetTag($xml_decoded, 'amount')?_T('alohacart_payment_liqpay:amount').': '.$amount."\n":'';
		$string .= $currency = $this->GetTag($xml_decoded, 'currency')?_T('alohacart_payment_liqpay:currency').': '.$currency."\n":'';
		$string .= $description = $this->GetTag($xml_decoded, 'description')?_T('alohacart_payment_liqpay:description').': '.$description."\n":'';
		$string .= $description = $this->GetTag($xml_decoded, 'status')?_T('alohacart_payment_liqpay:status').': '.$status."\n":'';
		$string .= $description = $this->GetTag($xml_decoded, 'code')?_T('alohacart_payment_liqpay:code').': '.$status."\n":'';		
        return $string;*/
    }
	
	/**
	 *  Parses xml tag and returns its content
	 *  @param string $text Parsed text
	 *  @param string $tag Tag to parse
	 *  @return string Parced value 
	 */
	public function GetTag($text, $tag) {
		preg_match('/<'.$tag.'>(.*)<\/'.$tag.'>/i', $text, $out);
		return $out[1];
	}
}
?>